package com.zty.xiaomiadmin.server.Service.User;

import com.zty.xiaomiadmin.server.Dao.User;
import com.zty.xiaomiadmin.server.Vo.User.UserData;
import com.zty.xiaomiadmin.server.Vo.User.UserResult;
import com.zty.xiaomiadmin.server.utils.SqlSessionUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;
import java.util.Random;

@Service
@Transactional
public class UserServiceImp implements UserService{


    @Override
    public UserResult getUsers() throws IOException {
        UserResult userResult = new UserResult();
        // 生成随机数
        Random random = new Random();
        int i = random.nextInt(9999);
        List<UserData> users = SqlSessionUtil.getNewSqlSessionInstance().getSqlSession().getMapper(User.class).getUsers(i);
        int userCount = SqlSessionUtil.getNewSqlSessionInstance().getSqlSession().getMapper(User.class).getUserCount();
        userResult.setPageTotal(userCount);
        userResult.setList(users);
        return userResult;
    }

    @Override
    public void editUser(UserData userData) {
        try {
            SqlSessionUtil.getSqlSessionInstance().getSqlSession().getMapper(User.class).editUser(userData);
            SqlSessionUtil.getSqlSessionInstance().getSqlSession().commit();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void delUser(String name) {
        try {
            SqlSessionUtil.getSqlSessionInstance().getSqlSession().getMapper(User.class).delUser(name);
            SqlSessionUtil.getSqlSessionInstance().getSqlSession().commit();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
